﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Business.Schedule
{
    public class CountdownScheduler : BaseScheduler
    {

        private readonly int _maxScheduleCount;
        private int _scheduleInterval;
        private readonly object _lockObj = new object();


        public CountdownScheduler(int scheduleInterval, int maxScheduleCount)
        {
            _scheduleInterval = scheduleInterval;
            _maxScheduleCount = maxScheduleCount;
        }

        public new void Start()
        {
            lock (_lockObj)
            {
                ScheduleCount = 0;
                base.Start();
                UpdateTimerInterval();
            }
        }

        public override void Schedule()
        {
            lock (_lockObj)
            {
                if (ScheduleCount >= _maxScheduleCount)
                    return;

                ScheduleCount++;
                scheduleAction?.Invoke(ScheduleCount);

                if (ScheduleCount >= _maxScheduleCount)
                {
                    base.Stop();
                }
            }
        }

        private void UpdateTimerInterval()
        {
            var timerField = typeof(BaseScheduler).GetField("timer",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

            var timer = (System.Timers.Timer)timerField?.GetValue(this);
            timer.Interval = _scheduleInterval;
        }

        public override Action<int> scheduleAction { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

 

    }
}
